
package com.tianyang.yukuaifu.utils;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class DeviceUtil {
    public static int SCREEN_WIDTH_PIXELS;
    public static int SCREEN_HEIGHT_PIXELS;
    public static float SCREEN_DENSITY;
    public static int SCREEN_WIDTH_DP;
    public static int SCREEN_HEIGHT_DP;
    private static boolean sInitialed;

    public static final String NETWORK_TYPE_2G = "2G";
    public static final String NETWORK_TYPE_3G = "3G";
    public static final String NETWORK_TYPE_WIFI = "WIFI";

    public static void init(Context context) {
        if (sInitialed || context == null) {
            return;
        }
        sInitialed = true;
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
        SCREEN_WIDTH_PIXELS = dm.widthPixels;
        SCREEN_HEIGHT_PIXELS = dm.heightPixels;
        SCREEN_DENSITY = dm.density;
        SCREEN_WIDTH_DP = (int) (SCREEN_WIDTH_PIXELS / dm.density);
        SCREEN_HEIGHT_DP = (int) (SCREEN_HEIGHT_PIXELS / dm.density);
    }

    public static int dp2px(float dp) {
        final float scale = SCREEN_DENSITY;
        return (int) (dp * scale + 0.5f);
    }

    public static int designedDP2px(float designedDp) {
        if (SCREEN_WIDTH_DP != 320) {
            designedDp = designedDp * SCREEN_WIDTH_DP / 320f;
        }
        return dp2px(designedDp);
    }

    public static void setPadding(final View view, float left, float top, float right, float bottom) {
        view.setPadding(designedDP2px(left), dp2px(top), designedDP2px(right), dp2px(bottom));
    }

    /*
     * 基础： px (Pixel像素) Screen Size (屏幕尺寸) Resolution (分辨率) 垂直水平方向像素个数 480*320
     * Dpi (dots per inch 像素密度) 每英寸像素数 对应 dm.densityDpi值 Density (密度) 每平方英寸像素数
     * Density = Resolution / Screen Size 对应 dm.density = dpi/160 Dip
     * (Device-independent-pixel 等同dp 设备独立像素) dip = 设备密度/160*pixel
     */


    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp px2dip 除以scale
     */
    public static int px2dip(float pxValue) {
        final float scale = SCREEN_DENSITY;
        return (int) (pxValue / scale + 0.5f);
    }

    public static boolean isConnect(Context context) {
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                // 获取网络连接管理的对象
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    // 判断当前网络是否已经连接
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {

        }
        return false;
    }

    //判断当前设备是否是模拟器。如果返回TRUE，则当前是模拟器，不是返回FALSE
    public static boolean isEmulator(Context context) {
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            String imei = tm.getDeviceId();
            if (imei != null && imei.equals("000000000000000")) {
                return true;
            }
            return (Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk"));
        } catch (Exception ioe) {

        }
        return false;
    }

    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    public static boolean isGingerbread() {
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB;
    }

    public static boolean isSandwich() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1;
    }

    /**
     * Check Network Type
     *
     * @param context
     * @return Network Type Label
     */
    public static String checkNetType(Context context) {
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info == null) {
                    return "";
                }
                if (!info.isAvailable()
                        || info.getState() == NetworkInfo.State.CONNECTED) {
                    if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                        switch (info.getSubtype()) {
                            case TelephonyManager.NETWORK_TYPE_1xRTT:
                                return NETWORK_TYPE_2G; // 2G ~ 50-100 kbps
                            case TelephonyManager.NETWORK_TYPE_CDMA:
                                return NETWORK_TYPE_2G; // 2G ~ 14-64 kbps
                            case TelephonyManager.NETWORK_TYPE_EDGE:
                                return NETWORK_TYPE_2G; // 2G ~ 50-100 kbps
                            case TelephonyManager.NETWORK_TYPE_GPRS:// 移动
                                return NETWORK_TYPE_2G; // 2G ~ 100 kbps
                            case TelephonyManager.NETWORK_TYPE_EVDO_0:
                                return NETWORK_TYPE_3G; // 3G ~ 400-1000
                            // kbps
                            case TelephonyManager.NETWORK_TYPE_EVDO_A:
                                return NETWORK_TYPE_3G; // 3G ~ 600-1400
                            // kbps
                            case TelephonyManager.NETWORK_TYPE_HSDPA:
                                return NETWORK_TYPE_3G; // 3G ~ 2-14 Mbps
                            case TelephonyManager.NETWORK_TYPE_HSPA:
                                return NETWORK_TYPE_3G; // 3G ~ 700-1700
                            // kbps
                            case TelephonyManager.NETWORK_TYPE_HSUPA:
                                return NETWORK_TYPE_3G; // 3G ~ 1-23 Mbps
                            case TelephonyManager.NETWORK_TYPE_UMTS:
                                return NETWORK_TYPE_3G; // 3G ~ 400-7000
                            // kbps
                            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
                                return "NETWORK_TYPE_UNKNOWN";

                            default:
                                return "MOBILE";
                        }
                    } else {
                        switch (info.getType()) {
                            case ConnectivityManager.TYPE_WIFI:
                                return NETWORK_TYPE_WIFI;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    public static String getNetType(Context context) {
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                        switch (info.getSubtype()) {
                            case TelephonyManager.NETWORK_TYPE_1xRTT:
                            case TelephonyManager.NETWORK_TYPE_CDMA:// 电信2g
                                return "2G_CDMA"; // 2G ~ 14-64 kbps
                            case TelephonyManager.NETWORK_TYPE_EDGE:// 联通2g
                                return "2G_EDGE"; // 2G ~ 50-100 kbps
                            case TelephonyManager.NETWORK_TYPE_GPRS:// 移动2g
                                return "2G_GPRS"; // 2G ~ 100 kbps
                            case TelephonyManager.NETWORK_TYPE_EVDO_0:// 电信3g
                            case TelephonyManager.NETWORK_TYPE_EVDO_A:
                            case TelephonyManager.NETWORK_TYPE_HSDPA:
                            case TelephonyManager.NETWORK_TYPE_HSPA:
                            case TelephonyManager.NETWORK_TYPE_HSUPA:
                            case TelephonyManager.NETWORK_TYPE_UMTS:// 联通 3g
                                return "3G_UMTS"; // 3G ~ 400-7000 kbps
                            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
                                return "NETWORK_TYPE_UNKNOWN";
                        }
                    } else {
                        switch (info.getType()) {
                            case ConnectivityManager.TYPE_WIFI:
                                return "TYPE_WIFI";
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    /**
     * 获取系统所有安装包名
     *
     * @param context
     * @return
     */
    public static List<String> getInstalledPackage(Context context) {
        List<PackageInfo> appPackage = context.getPackageManager()
                .getInstalledPackages(0);
        List<String> packageList = new ArrayList<String>();
        for (int i = 0; i < appPackage.size(); i++) {
            PackageInfo packageInfo = appPackage.get(i);
            String appName = packageInfo.packageName;
            packageList.add(appName);
            // packageInfo.applicationInfo.name
            // packageInfo.applicationInfo.loadLabel(getPackageManager()).toString();
        }
        return packageList;
    }

    /**
     * 检查系统有没安装某个包
     *
     * @param context
     * @param packagename
     * @return
     */
    public static boolean checkInstalledPackage(Context context,
                                                String packagename) {
        List<PackageInfo> appPackage = context.getPackageManager()
                .getInstalledPackages(0);
        for (int i = 0; i < appPackage.size(); i++) {
            PackageInfo packageInfo = appPackage.get(i);
            String packageName = packageInfo.packageName;
            if (packageName.equals(packagename)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取系统所有应用名
     *
     * @param context
     * @return
     */
    public static List<String> getInstalledAppName(Context context) {
        List<PackageInfo> appPackage = context.getPackageManager()
                .getInstalledPackages(0);
        List<String> packageList = new ArrayList<String>();
        for (int i = 0; i < appPackage.size(); i++) {
            PackageInfo packageInfo = appPackage.get(i);
            String appName = packageInfo.applicationInfo.loadLabel(
                    context.getPackageManager()).toString();
            packageList.add(appName);
        }
        return packageList;
    }

    public static int getSysVersion() {
        String phoneInfo = "Product: " + Build.PRODUCT;
        phoneInfo += ", CPU_ABI: " + Build.CPU_ABI;
        phoneInfo += ", TAGS: " + Build.TAGS;
        phoneInfo += ", VERSION_CODES.BASE: "
                + Build.VERSION_CODES.BASE;
        phoneInfo += ", MODEL: " + Build.MODEL;
        phoneInfo += ", SDK: " + Build.VERSION.SDK;
        phoneInfo += ", VERSION.RELEASE: " + Build.VERSION.RELEASE;
        phoneInfo += ", DEVICE: " + Build.DEVICE;
        phoneInfo += ", DISPLAY: " + Build.DISPLAY;
        phoneInfo += ", BRAND: " + Build.BRAND;
        phoneInfo += ", BOARD: " + Build.BOARD;
        phoneInfo += ", FINGERPRINT: " + Build.FINGERPRINT;
        phoneInfo += ", ID: " + Build.ID;
        phoneInfo += ", MANUFACTURER: " + Build.MANUFACTURER;
        phoneInfo += ", USER: " + Build.USER;
        int version = Build.VERSION_CODES.BASE;
        try {
            version = Integer.valueOf(Build.VERSION.SDK);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return version;
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
    public static boolean isAppOnForeground(String packageName, Context context) {
        // Returns a list of application processes that are running on the
        // device
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {

                return true;
            }
        }

        return false;
    }

    /**
     * 程序是否在前台运行
     *
     * @return
     */
//    public static String getCurrentActivity() {
//        ActivityManager manager = (ActivityManager) GlobalApplication.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
//        ActivityManager.RunningTaskInfo info = manager.getRunningTasks(1).get(0);
//        String shortClassName = info.topActivity.getShortClassName();    //类名
//        String className = info.topActivity.getClassName();              //完整类名
//        String packageName = info.topActivity.getPackageName();          //包名
//        return className;
//    }

    /**
     * 判断Sd卡是否存在
     *
     * @return
     */
    public static boolean isSDCARDMounted() {
        String status = Environment.getExternalStorageState();

        if (status.equals(Environment.MEDIA_MOUNTED))
            return true;
        return false;
    }

    /**
     * 判断是否支持NFC
     * @param context
     * @return
     */
    public static boolean isSupportNFC(Context context) {
        PackageManager packageManager = context.getPackageManager();
        return packageManager.hasSystemFeature(PackageManager.FEATURE_NFC);
    }

    public static boolean isMobileEnableReflex(Context context) {
        try {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            Method getMobileDataEnabledMethod = ConnectivityManager.class.getDeclaredMethod("getMobileDataEnabled");
            getMobileDataEnabledMethod.setAccessible(true);
            return (Boolean) getMobileDataEnabledMethod.invoke(connectivityManager);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
